package com.smart.manager.system.repository;


import cn.hutool.core.lang.Opt;
import com.smart.common.entities.core.Page;
import com.smart.manager.system.entities.body.RLogLogin;
import com.smart.manager.system.entities.body.RLogOperation;
import com.smart.manager.system.entities.models.SystemLoginLog;
import com.smart.manager.system.entities.models.SystemOperationLog;
import com.smart.manager.system.entities.models.query.QSystemLoginLog;
import com.smart.manager.system.entities.models.query.QSystemOperationLog;
import com.smart.utils.SqlUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 登陆日志
 *
 * @author quyi
 * @date 2022/11/18
 */
@Service
public class LogRepository {
    /**
     * 获得登录日志页面列表
     *
     * @param searchBody 搜索身体
     * @return {@link Page}<{@link SystemLoginLog}>
     */
    public Page<SystemLoginLog> getLoginLogPageList(RLogLogin.SearchBody searchBody) {
        QSystemLoginLog query = new QSystemLoginLog();
        Opt.ofBlankAble(searchBody.getIp()).ifPresent(x -> query.ip.contains(x));
        Opt.ofBlankAble(searchBody.getAccount()).ifPresent(x -> query.account.contains(x));
        Opt.ofBlankAble(searchBody.getDateRange()).ifPresent(x -> {
            LocalDateTime[] times = SqlUtil.formatDateTimeRange(x);
            query.loginTime.between(times[0], times[1]);
        });
        query.setFirstRow(searchBody.firstRow()).setMaxRows(searchBody.maxRows());
        query.order().id.desc();
        return new Page<SystemLoginLog>().load(query.findPagedList());

    }

    /**
     * 分页查询日志列表页
     *
     * @param searchBody 搜索身体
     * @return {@link Page}<{@link SystemOperationLog}>
     */
    public Page<SystemOperationLog> getOperationLogPageList(RLogOperation.SearchBody searchBody) {
        QSystemOperationLog query = new QSystemOperationLog();
        Opt.ofBlankAble(searchBody.getIp()).ifPresent(x -> query.ip.contains(x));
        Opt.ofBlankAble(searchBody.getOperator()).ifPresent(x -> query.operator.contains(x));
        Opt.ofBlankAble(searchBody.getPackageName()).ifPresent(x -> query.packageName.contains(x));
        Opt.ofBlankAble(searchBody.getDateRange()).ifPresent(x -> {
            LocalDateTime[] times = SqlUtil.formatDateTimeRange(x);
            query.actionTime.between(times[0], times[1]);
        });
        query.setFirstRow(searchBody.firstRow()).setMaxRows(searchBody.maxRows());
        query.order().id.desc();
        return new Page<SystemOperationLog>().load(query.findPagedList());

    }


}

